import qiniu from 'qiniu'
import chalk from 'chalk'
import { error } from 'util'
class Token {

    constructor(){
        this.domain = 'http://cdn.swellpro.cn'
        this.accessKey = "fT0BuCHvMpqbJPClibk-mbzRS3iXhVFr0GjbQHaJ" //access密钥一
        this.secretKey = "9OZj_KDnZdylQ8rEfDxrO_zbzagIOvpabRGZLQOh" //secret密钥二
        this.bucket = "liweiswellprobob1996" //七牛云空间名
        this.getToken = this.getToken.bind(this)
        this.refreshFileAndPushToCdn = this.refreshFileAndPushToCdn.bind(this)
    }

    getToken({params}, res, next){

        let { name } = params

        let options = {}
        options.scope = `${this.bucket}:blog/${name}`
        options.returnBody = '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'

        const mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey); //创建鉴权对象mac

        const putPolicy = new qiniu.rs.PutPolicy(options);

        const uploadToken = putPolicy.uploadToken(mac);

        res.send({
            status: 1,
            type: 'GET_TOKEN',
            message: uploadToken
        })
    }

    refreshFileAndPushToCdn({ params }, res, next){

        let { name } = params

        let urlsToRefresh = []

        let absoluteUrl = `${this.domain}/blog/${name}`

        urlsToRefresh.push(absoluteUrl)


        let mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);

        let cdnManager = new qiniu.cdn.CdnManager(mac);

        try{

            cdnManager.refreshUrls(urlsToRefresh, function (err, respBody, respInfo) {

                if (err) {
                    throw new Error(`刷新操作失败,因为 ${err}`) ;
                }

                if (respInfo.statusCode != 200) {
                    throw new Error(`刷新操作失败`);
                }
                
            });

            /*cdnManager.prefetchUrls(urlsToRefresh, function (err, respBody, respInfo) {

                if (err) {
                    throw new Error(`预取操作失败,因为 ${err}`);
                }

                if (respInfo.statusCode != 200) {
                    throw new Error(`预取操作失败`);
                }

            });*/

            res.send({
                status: 1,
                type: 'REFRESH_FILE_AND_PUSH_TO_CDN',
                message: '刷新缓存操作成功'
            })


        }catch(err){

            console.log(chalk.red(`刷新缓存操作失败,因为 ${err.message}`))

            res.send({
                status: 0,
                type: 'REFRESH_FILE_AND_PUSH_TO_CDN',
                message: err.message
            })

            return

        }

    }
}

export default new Token()